from celery import shared_task
import logging
from dvadmin.system.models import DownloadList, DownloadInfo
from urllib.request import urlretrieve
import os
from application import settings
import time
from urllib import parse
import zipfile
from asgiref.sync import sync_to_async

logger = logging.getLogger(__name__)


# @app.task(name='test')
def test_task():
    logger.info(
        '222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222')


# 开始下载任务
@shared_task
def download_start(ids=None):
    from dvadmin.system.models import DownloadList, DownloadInfo
    list_ids = ids

    if not list_ids:
        list_ids = DownloadList.objects.filter(status=1).values_list("id", flat=True)

    for id in list_ids:
        download_list_row = DownloadList.objects.get(pk=id)

        download_list_row.status = 2
        download_list_row.save()
        url_list = DownloadInfo.objects.filter(ydh_id=id).values("id", "ydh", "file_url")
        path = f"{settings.MEDIA_URL_DIRS}{id}/"
        mkdirFile(path)

        temp_url_list = []
        for url in url_list:
            if not url:
                continue

            download_info_row = DownloadInfo.objects.get(pk=url["id"])
            file_extension = url["file_url"].split(".")[-1].split("?")[0]
            print(f"{path}{url['id']}.{file_extension}")

            parse_url = parse.urlparse(url["file_url"])

            # 对参数解码，并重新转义 组装
            file_url = parse.urlunparse(
                [parse_url.scheme, parse_url.netloc, parse.quote(parse_url.path), parse_url.params,
                 parse_url.query, parse_url.fragment])

            try:

                urlretrieve(file_url, f"{path}{url['id']}.{file_extension}")

                temp_url_list.append(
                    {"full_url": f"{path}{url['id']}.{file_extension}", "save_name": f"{url['id']}.{file_extension}"})

                download_info_row.status = 3
                download_info_row.save()
            except OSError:
                download_info_row.status = 5 # 图片已过期
                download_info_row.save()

        # 打包
        zip_file_path = os.path.join(path, f'{id}.zip')
        with zipfile.ZipFile(zip_file_path, 'w') as zip_file:
            for file_name in temp_url_list:
                zip_file.write(file_name["full_url"], file_name["save_name"])

        download_list_row.export_url = f"/media/{id}/{id}.zip"
        download_list_row.status = 3
        download_list_row.save()


def mkdirFile(path):
    # 判断该路径的文件夹是否存在
    folder = os.path.exists(path)
    # 如果不存在则新建
    if not folder:
        os.makedirs(path)
    else:
        delete_files_in_folder(path)
        os.makedirs(path)


def delete_files_in_folder(folder_path):
    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)
        if os.path.isfile(file_path):
            os.remove(file_path)
